package com.ktjy.car.controller;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.ktjy.car.entity.Login;
import com.ktjy.car.entity.vo.R;
import com.ktjy.car.service.LoginService;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@CrossOrigin
@RestController
public class LoginController {
    @Resource
    private LoginService loginService;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    private static final long TOKEN_EXPIRE_TIME = 30 * 60; // token有效期半小时

    @PostMapping("/login")  // 修改为 PostMapping
    public R login(@RequestBody Login login) {
        int result = loginService.login(login);
        if (result != 0) {
            // 生成token
            String token = UUID.randomUUID().toString();
            //将用户信息存入Redis，设置过期时间
            String redisKey = "token:" + token;
            redisTemplate.opsForValue().set(redisKey, result, TOKEN_EXPIRE_TIME, TimeUnit.SECONDS);
            //构建返回数据
            Map<String, Object> data = new HashMap<>();
            data.put("token", token);
            return R.ok(data);
        }
        return R.fail("账号或密码错误");
    }

    @PostMapping("/logout")
    public R logout(@RequestHeader("Authorization") String token) {
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7);
            String redisKey = "token:" + token;
            // 从Redis中删除token
            redisTemplate.delete(redisKey);
            return R.ok("退出登录成功");
        }
        return R.fail("退出登录失败");
    }
}
